import 'dart:convert';

import 'package:open_source_china/model/user.dart';
import 'package:shared_preferences/shared_preferences.dart';

class DataUtils {
  static const String ACCESS_TOKEN = "access_token";
  static const String REFRESH_TOKEN = "refresh_token";
  static const String UID = "uid";
  static const String TOKEN_TYPE = "token_type";
  static const String EXPIRES_IN = "expires_in";
  static const String IS_LOGIN = "is_login";
  static const String USER_INFO = "user_info";

  /// 保存登录信息
  static Future<void> setLoginInfo(
      {Map<String, dynamic> map, bool clear = false}) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp
      ..setString(ACCESS_TOKEN, clear ? '' : map[ACCESS_TOKEN])
      ..setString(REFRESH_TOKEN, clear ? '' : map[REFRESH_TOKEN])
      ..setInt(UID, clear ? -1 : map[UID])
      ..setString(TOKEN_TYPE, clear ? '' : map[TOKEN_TYPE])
      ..setInt(EXPIRES_IN, clear ? -1 : map[EXPIRES_IN]);
  }

  /// 保存用户信息
  static Future<bool> saveUserInfo(User user) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    String data = jsonEncode(user);
    return await sp.setString(USER_INFO, data);
  }

  /// 获取用户信息
  static Future<User> getUserInfo() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    String str = sp.getString(USER_INFO);
    if (str == null || str.length == 0) return null;
    Map map = json.decode(str);
    User user = User.fromJson(map);
    return user;
  }

  /// 删除用户信息，并退出登录
  static Future<void> logout() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    setLoginInfo(map: null, clear: true);
    sp.remove(USER_INFO);
    // sp.remove(ACCESS_TOKEN);
    // sp.remove(REFRESH_TOKEN);
    // sp.remove(UID);
    // sp.remove(TOKEN_TYPE);
    // sp.remove(EXPIRES_IN);
    // sp.remove(IS_LOGIN);
  }

  /// 是否已登录
  static Future<bool> hasLogin() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    String token = sp.getString(ACCESS_TOKEN);
    bool isLogin = token != null && token != '';
    return isLogin;
  }

  /// 获取 SharedPreferences 数据
  static Future<dynamic> get(String key) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    var value = sp.get(key);
    return value;
  }

  /// 获取token
  static Future<String> getToken() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    String token = sp.getString(ACCESS_TOKEN);
    return token;
  }
}
